const express = require('express');
const router = express.Router();
const { authenticate } = require('../middleware/auth');
const db = require('../config/database');
const { successResponse, errorResponse } = require('../utils/response');

// 管理员中间件 - 验证是否是管理员
const requireAdmin = async (req, res, next) => {
  if (!req.user.isAdmin) {
    return errorResponse(res, '需要管理员权限', 403);
  }
  next();
};

// 所有管理员路由都需要认证和管理员权限
router.use(authenticate);
router.use(requireAdmin);

/**
 * 获取统计数据
 */
router.get('/stats', async (req, res) => {
  try {
    // 总用户数
    const [userCount] = await db.execute('SELECT COUNT(*) as count FROM users');
    
    // 总单词数
    const [wordCount] = await db.execute('SELECT COUNT(*) as count FROM vocabulary');
    
    // 总成就数
    const [achievementCount] = await db.execute('SELECT COUNT(*) as count FROM achievements');
    
    // 今日活跃用户（今天登录过的）
    const [activeCount] = await db.execute(
      'SELECT COUNT(*) as count FROM users WHERE DATE(last_login) = CURDATE()'
    );

    const stats = {
      totalUsers: userCount[0].count,
      totalWords: wordCount[0].count,
      totalAchievements: achievementCount[0].count,
      todayActive: activeCount[0].count
    };

    return successResponse(res, stats);
  } catch (error) {
    console.error('获取统计数据失败:', error);
    return errorResponse(res, '获取统计数据失败', 500, error);
  }
});

/**
 * 获取所有用户列表
 */
router.get('/users', async (req, res) => {
  try {
    const { page = 1, limit = 100, search = '' } = req.query;
    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 100;
    const offsetNum = Math.max(0, (pageNum - 1) * limitNum);

    let query = `
      SELECT 
        id, username, school, grade, avatar, stars,
        total_correct, total_wrong, continuous_days,
        last_login, created_at
      FROM users
    `;
    
    const params = [];
    
    if (search && search.trim()) {
      query += ' WHERE username LIKE ? OR school LIKE ?';
      params.push(`%${search}%`, `%${search}%`);
    }
    
    // 使用字符串拼接处理LIMIT和OFFSET，避免参数类型问题
    query += ` ORDER BY created_at DESC LIMIT ${limitNum} OFFSET ${offsetNum}`;

    console.log('SQL查询:', query);
    console.log('SQL参数:', params);

    const [users] = await db.execute(query, params);
    
    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM users';
    const countParams = [];
    if (search) {
      countQuery += ' WHERE username LIKE ? OR school LIKE ?';
      countParams.push(`%${search}%`, `%${search}%`);
    }
    const [countResult] = await db.execute(countQuery, countParams);

    return successResponse(res, {
      users,
      total: countResult[0].total,
      page: pageNum,
      limit: limitNum
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    return errorResponse(res, '获取用户列表失败', 500, error);
  }
});

/**
 * 获取单个用户详情
 */
router.get('/users/:userId', async (req, res) => {
  try {
    const { userId } = req.params;

    const [users] = await db.execute(
      `SELECT 
        u.*,
        COUNT(DISTINCT up.word_id) as words_learned,
        AVG(up.mastery_level) as avg_mastery
      FROM users u
      LEFT JOIN user_progress up ON u.id = up.user_id
      WHERE u.id = ?
      GROUP BY u.id`,
      [userId]
    );

    if (users.length === 0) {
      return errorResponse(res, '用户不存在', 404);
    }

    // 获取用户的宠物信息
    const [pets] = await db.execute(
      'SELECT * FROM pets WHERE user_id = ?',
      [userId]
    );

    // 获取用户的成就
    const [achievements] = await db.execute(
      `SELECT a.* 
       FROM achievements a
       INNER JOIN user_achievements ua ON a.id = ua.achievement_id
       WHERE ua.user_id = ?`,
      [userId]
    );

    return successResponse(res, {
      user: users[0],
      pet: pets[0] || null,
      achievements
    });
  } catch (error) {
    console.error('获取用户详情失败:', error);
    return errorResponse(res, '获取用户详情失败', 500, error);
  }
});

/**
 * 删除用户
 */
router.delete('/users/:userId', async (req, res) => {
  const connection = await db.getConnection();
  try {
    await connection.beginTransaction();

    const { userId } = req.params;

    // 删除相关数据
    await connection.execute('DELETE FROM user_progress WHERE user_id = ?', [userId]);
    await connection.execute('DELETE FROM user_achievements WHERE user_id = ?', [userId]);
    await connection.execute('DELETE FROM pets WHERE user_id = ?', [userId]);
    await connection.execute('DELETE FROM game_records WHERE user_id = ?', [userId]);
    await connection.execute('DELETE FROM friendships WHERE user_id = ? OR friend_id = ?', [userId, userId]);
    await connection.execute('DELETE FROM daily_tasks WHERE user_id = ?', [userId]);
    await connection.execute('DELETE FROM users WHERE id = ?', [userId]);

    await connection.commit();

    // 记录操作日志
    await db.execute(
      'INSERT INTO admin_logs (admin_id, action, details) VALUES (?, ?, ?)',
      [req.user.id, 'delete_user', `删除用户ID: ${userId}`]
    );

    return successResponse(res, null, '用户删除成功');
  } catch (error) {
    await connection.rollback();
    console.error('删除用户失败:', error);
    return errorResponse(res, '删除用户失败', 500, error);
  } finally {
    connection.release();
  }
});

/**
 * 获取操作日志
 */
router.get('/logs', async (req, res) => {
  try {
    const { page = 1, limit = 50 } = req.query;
    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 50;
    const offsetNum = Math.max(0, (pageNum - 1) * limitNum);

    const [logs] = await db.execute(
      `SELECT 
        al.*,
        a.username as admin_username,
        a.real_name as admin_name
      FROM admin_logs al
      INNER JOIN admins a ON al.admin_id = a.id
      ORDER BY al.created_at DESC
      LIMIT ${limitNum} OFFSET ${offsetNum}`
    );

    const [countResult] = await db.execute('SELECT COUNT(*) as total FROM admin_logs');

    return successResponse(res, {
      logs,
      total: countResult[0].total,
      page: pageNum,
      limit: limitNum
    });
  } catch (error) {
    console.error('获取操作日志失败:', error);
    return errorResponse(res, '获取操作日志失败', 500, error);
  }
});

module.exports = router;

